package com.ynding.cloud.auth.api.admin.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ynding.cloud.auth.api.admin.entity.Role;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ynding
 */
@Data
@Builder
@ApiModel(value = "User", description = "用户")
@NoArgsConstructor
@AllArgsConstructor
public class UserDO implements UserDetails, Principal, Serializable {

    private static final long serialVersionUID = -5036276353119363765L;
    @ApiModelProperty(name = "id", notes = "ID", dataType = "long")
    private Long id;
    private String name;
    private String phone;
    private String telephone;
    private String address;
    @NotNull
    private int enabled;
    private String username;
    private String password;
    private String remark;
    private String userface;

    private List<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public String getName() {
        return username;
    }

    /**
     * 账户是否过期
     */
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {//账户是否锁定
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {//密码是否过期
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled == 1;
    }
}
